package com.fyl.core.advance.constant.enums;


import com.fyl.core.advance.exception.BaseException;
import com.fyl.core.advance.exception.assertion.CommonExceptionAssert;
import com.fyl.core.response.BaseResponse;

/**
 * <p>通用返回结果</p>
 *
 * @author sprainkle
 * @date 2019/5/2
 */
public enum CommonResponseEnum implements CommonExceptionAssert {

    //成功
    SUCCESS(200, "SUCCESS"),
    //失败
    FAIL(400, "ERROR"),
    //未认证（签名错误）
    UNAUTHORIZED(401, "Authentication failed"),

    FORBIDDEN(403, "Forbidden"),
    //接口不存在
    NOT_FOUND(404, "APi not find"),
    //服务器内部错误
    INTERNAL_SERVER_ERROR(500, "Server Error"),

    // Time
    DATE_NOT_NULL(1001, "日期不能为空"),
    DATETIME_NOT_NULL(1001, "时间不能为空"),
    TIME_NOT_NULL(1001, "时间不能为空"),
    DATE_PATTERN_MISMATCH(1002, "日期[%s]与格式[%s]不匹配，无法解析"),
    PATTERN_NOT_NULL(1003, "日期格式不能为空"),
    PATTERN_INVALID(1003, "日期格式[%s]无法识别"),


    ;

    /**
     * 返回码
     */
    private int code;
    /**
     * 返回消息
     */
    private String message;

    CommonResponseEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    /**
     * 校验返回结果是否成功
     *
     * @param response 远程调用的响应
     */
    public static void assertSuccess(BaseResponse response) {
        INTERNAL_SERVER_ERROR.assertNotNull(response);

        int code = response.getCode();
        if (CommonResponseEnum.SUCCESS.getCode() != code) {
            String msg = response.getMessage();
            throw new BaseException(code, msg);
        }
    }
}
